//
//  GlobalManager.m
//  Dresshere
//
//  Created by ZhangPeng on 2017/12/28.
//  Copyright © 2017年 张朋. All rights reserved.
//

#import "GlobalManager.h"
#import "Version.h"
#import "Vip.h"
#import "UpYunFormUploader.h"

@implementation GlobalManager

static GlobalManager *_shareClient = nil;
static dispatch_once_t onceToken;

+ (GlobalManager *)shareGlobalManager{
    dispatch_once(&onceToken, ^{
        _shareClient = [[GlobalManager alloc] init];
        _shareClient.refreshImagesArray = @[@"1.png",@"2.png",@"3.png",@"4.png",@"5.png",@"6.png",@"7.png",@"8.png",@"9.png",@"10.png",@"11.png",@"12.png",@"13.png",@"14.png",@"15.png",@"16.png",@"17.png",];
    });
    return _shareClient;
}

- (NSArray *)supportCitiesArray{
    if (!_supportCitiesArray) {
        _supportCitiesArray = [NSArray array];
    }
    return _supportCitiesArray;
}

- (NSArray *)logisticsArray{
    if (!_logisticsArray) {
        _logisticsArray = [NSArray array];
    }
    return _logisticsArray;
}

- (void)refreshVersion{
    [[DHNetAPIClient shareDHNetAPIClient] request_versionAndBlock:^(id data, NSError *error) {
        self.version = [Version modelWithDictionary:data];
        NSLog(@"%@",self.version.version);
    }];
}

- (void)refreshSupportCities{
    [[DHNetAPIClient shareDHNetAPIClient] request_supportCitiesAndBlock:^(id data, NSError *error) {
        self.supportCitiesArray = [data objectForKey:@"cities"];
    }];
}

- (void)refreshlogistics{
    [[DHNetAPIClient shareDHNetAPIClient] request_logisticsAndBlock:^(id data, NSError *error) {
        self.logisticsArray = [data objectForKey:@"logistics"];
    }];
}

- (void)refreshBasicInfoAndBlock:(void (^)(id, NSError *))block{
    [[DHNetAPIClient shareDHNetAPIClient] request_basicInfoAndBlock:^(id data, NSError *error) {
        self.user = [User modelWithDictionary:[data objectForKey:@"user"]];
        [Login doLogin:self.user];
        block(data, error);
    }];
}

- (void)refreshVIPInfoAndBlock:(void (^)(id data, NSError *error))block{
    [[DHNetAPIClient shareDHNetAPIClient] request_vipAndBlock:^(id data, NSError *error) {
        if ([[data objectForKey:@"subscription"] objectForKey:@"_id"]) {
            Vip *vip = [[Vip alloc] init];
            vip.vip = YES;
            vip.info = [data objectForKey:@"subscription"];
            self.vip = vip;
        }else{
            self.vip = nil;
        }
        block(data, error);
    }];
}

- (void)refreshCartNumberAndBlock:(void (^)(id, NSError *))block{
    [[DHNetAPIClient shareDHNetAPIClient] request_cart_countAndBlock:^(id data, NSError *error) {
        self.cartNumber = [[data objectForKey:@"count"] integerValue];
        block(data, error);
        postN(@"refresh_cart");
    }];
}

- (void)refreshDepositAndBlock:(void (^)(id, NSError *))block{
    [[DHNetAPIClient shareDHNetAPIClient] request_user_depositAndBlock:^(id data, NSError *error) {
        self.deposit = [[data objectForKey:@"deposit"] floatValue];
        block(data, error);
    }];
}

- (void)refreshNotificationsUnreadCountAndBlock:(void (^)(id data, NSError *error))block{
    [[DHNetAPIClient shareDHNetAPIClient] request_notifications_unread_countAndBlock:^(id data, NSError *error) {
        self.notificationsUnreadCount = [[data objectForKey:@"unread"] integerValue];
        block(data, error);
    }];
}

- (void)upyunUploadImage:(UIImage *)image andBlock:(void (^)(id data, NSError *error))block{
    NSData *fileData = [self compressWithOrgImg:image];
    UpYunFormUploader *up = [[UpYunFormUploader alloc] init];
    
    NSDate *date = [NSDate dateWithTimeIntervalSinceNow:0];//获取当前时间0秒后的时间
    NSTimeInterval time=[date timeIntervalSince1970]*1000;// *1000 是精确到毫秒，不乘就是精确到秒
    NSString *timeString = [NSString stringWithFormat:@"%.0f", time];
    
    NSString *bucketName = @"dresshere";
    [up uploadWithBucketName:bucketName
                    operator:@"admin"
                    password:@"yang140034"
                    fileData:fileData
                    fileName:nil
                     saveKey:[NSString stringWithFormat:@"social/%@.jpg",timeString]
             otherParameters:nil
                     success:^(NSHTTPURLResponse *response,
                               NSDictionary *responseBody) {
                         //主线程刷新ui
                         NSString *url = [NSString stringWithFormat:@"http://cdn.%@.cn/%@", bucketName, [responseBody objectForKey:@"url"]];
                         block(url, nil);
                     }
                     failure:^(NSError *error,
                               NSHTTPURLResponse *response,
                               NSDictionary *responseBody) {
                         NSLog(@"上传失败 error：%@", error);
                         NSLog(@"上传失败 code=%ld, responseHeader：%@", (long)response.statusCode, response.allHeaderFields);
                         NSLog(@"上传失败 message：%@", responseBody);
                         //主线程刷新ui
                         dispatch_async(dispatch_get_main_queue(), ^(){
                             NSString *message = [responseBody objectForKey:@"message"];
                             [NSObject showHudTipStr:message];
                         });
                     }
     
                    progress:^(int64_t completedBytesCount,
                               int64_t totalBytesCount) {
                        NSString *progress = [NSString stringWithFormat:@"%lld / %lld", completedBytesCount, totalBytesCount];
                        NSString *progress_rate = [NSString stringWithFormat:@"upload %.1f %%", 100 * (float)completedBytesCount / totalBytesCount];
                        NSLog(@"upload progress: %@", progress);
                        
                        //主线程刷新ui
                        dispatch_async(dispatch_get_main_queue(), ^(){
                            
                        });
                    }];
    
}

- (NSData *)compressWithOrgImg:(UIImage *)img
{
    
    NSData *imageData = UIImageJPEGRepresentation(img, 1);
    float length = imageData.length;
    length = length/1024;
    NSLog(@"压缩前的大小：%fKB",length);
    // 裁剪比例
    CGFloat cout = 0.5;
    
    // 压缩比例
    CGFloat imgCout = 0.1;
    if(length > 25000){ // 25M以上的图片
        cout = 0.1;
        imgCout = 0;
    }else if(length > 10000){ // 10M以上的图片
        cout = 0.2;
        imgCout = 0;
    }else if (length > 5000) { // 5M以上的图片
        cout = 0.3;
        imgCout = 0;
    }else if (length > 1500) { // 如果原图大于1.5M就换一个压缩级别
        cout = 0.7;
        imgCout = 0.1;
    }else if (length > 1000) {
        cout = 0.8;
        imgCout = 0.2;
    }else if (length > 500) {
        cout = 0.8;
        imgCout = 0.3;
    }else if (length >100){ // 小于500k的不用裁剪
        
        imageData = UIImageJPEGRepresentation(img, 50 / imageData.length);
        float length = imageData.length;
        length = length/1024;
        NSLog(@"压缩后的大小：%fKB",length);
        return imageData;
    }else{
        
        imageData = UIImageJPEGRepresentation(img, 0.5);
        float length = imageData.length;
        length = length/1024;
        NSLog(@"压缩后的大小：%fKB",length);
        return imageData;
    }
    
    
    // 按裁剪比例裁剪
    UIImage *compressImage =  [self imageByScalingAndCroppingForSize:CGSizeMake(img.size.width * cout, img.size.height *cout) sourceImage:img];
    
    
    // 那压缩比例压缩
    imageData = UIImageJPEGRepresentation(compressImage, imgCout);
    
    length= imageData.length / 1024;
    NSLog(@"裁剪比例：%f，压缩比例：%f,压缩后的大小：%fKB",cout,imgCout,length);
    return imageData;
}

// 裁剪
- (UIImage*)imageByScalingAndCroppingForSize:(CGSize)targetSize sourceImage:(UIImage *)sImage
{
    UIImage *sourceImage = sImage;
    UIImage *newImage = nil;
    CGSize imageSize = sourceImage.size;
    CGFloat width = imageSize.width;
    CGFloat height = imageSize.height;
    CGFloat targetWidth = targetSize.width;
    CGFloat targetHeight = targetSize.height;
    CGFloat scaleFactor = 0.0;
    CGFloat scaledWidth = targetWidth;
    CGFloat scaledHeight = targetHeight;
    CGPoint thumbnailPoint = CGPointMake(0.0,0.0);
    
    if (CGSizeEqualToSize(imageSize, targetSize) == NO)
    {
        CGFloat widthFactor = targetWidth / width;
        CGFloat heightFactor = targetHeight / height;
        
        if (widthFactor > heightFactor)
            scaleFactor = widthFactor; // scale to fit height
        else
            scaleFactor = heightFactor; // scale to fit width
        scaledWidth= width * scaleFactor;
        scaledHeight = height * scaleFactor;
        
        // center the image
        if (widthFactor > heightFactor)
        {
            thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;
        }
        else if (widthFactor < heightFactor)
        {
            thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
        }
    }
    
    UIGraphicsBeginImageContext(targetSize); // this will crop
    
    CGRect thumbnailRect = CGRectZero;
    thumbnailRect.origin = thumbnailPoint;
    thumbnailRect.size.width= scaledWidth;
    thumbnailRect.size.height = scaledHeight;
    
    [sourceImage drawInRect:thumbnailRect];
    
    newImage = UIGraphicsGetImageFromCurrentImageContext();
    if(newImage == nil)
        NSLog(@"could not scale image");
    
    //pop the context to get back to the default
    UIGraphicsEndImageContext();
    return newImage;
}

@end
